import { mountStoreDevtool } from 'simple-zustand-devtools';
import { create } from 'zustand';

import MenuItems from '../layout/Menu/MenuProps';
import { getMenu } from '../api/user';
import React from 'react';
import * as Icon from '@ant-design/icons';
import { routers } from '../router';
import { lazy } from 'react';
import { deepClone } from '../utils';

interface LayoutStore {
  collapsed: boolean; // 侧边折叠
  menus: any[]; // 菜单
  myRouters: any[];
  isLoadingMenus: boolean;
  getMenus: () => void;
  setCollapsed: () => void;
  setLoadingMenus: (loading: boolean) => void;
}

function menuFn(arr: any[]) {
  const menu: any[] = [];
  arr.forEach((item) => {
    menu.push({
      label: item.name,
      key: item.url,
      icon: React.createElement(Icon['HomeOutlined']),
      children: item.children.length ? menuFn(item.children) : null,
    });
    if (item.children) {
      menuFn(item.children);
    }
  });
  return menu;
}


// 快速导入工具函数
export const lazyLoad = (moduleName: string) => {
  const Module = lazy(() => import(`../views/${moduleName}.tsx`));
  return <Module />;
};

const _routers: any[] = [];
function routerFn(arr: any) {
  arr.forEach((item: any) => {
    if (item.node_type === 1) {
      _routers.push({
        id: item.id,
        path: item.assembly_url,
        name: item.assembly_name,
        auth: true,
        element: item.assembly_url//lazyLoad(item.assembly_url),
      });
    }
    if (item.children) {
      routerFn(item.children);
    }
  });
}

const useLayoutStore = create<LayoutStore>((set, get) => ({
  collapsed: false,
  menus: [],
  myRouters: [],
  isLoadingMenus: false,
  setCollapsed: () => set((state) => ({ collapsed: !state.collapsed })),
  getMenus: async () => {
    const getToken = localStorage.getItem('useUserStore');
    const token = getToken ? JSON.parse(getToken).state.token : '';
    if (!token) {
      set({ menus: [...MenuItems] });
      return;
    }
    const res = await getMenu().catch((err) => {
      console.log(err);
    });
    if (res?.success) {
      set({ menus: [...MenuItems, ...menuFn(res.data)] });
    }
  },
  setLoadingMenus: (loading) => {
    set({ isLoadingMenus: loading });
  },
}));

mountStoreDevtool('useLayoutStore', useLayoutStore);
export default useLayoutStore;
